<template>
  <div class="book-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑图书' : '添加图书' }}</h2>
      <el-button @click="goBack">返回</el-button>
    </div>

    <div v-loading="loading">
      <el-skeleton :rows="8" animated v-if="loading && isEdit" />

      <el-form
        v-else
        ref="bookFormRef"
        :model="bookForm"
        :rules="rules"
        label-width="100px"
        class="book-form"
      >
        <!-- 基本信息部分 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="书名" prop="title">
                <el-input v-model="bookForm.title" placeholder="请输入书名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作者" prop="author">
                <el-input v-model="bookForm.author" placeholder="请输入作者" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分类" prop="category">
                <el-select v-model="bookForm.category" placeholder="请选择分类" style="width: 100%">
                  <el-option label="文学" value="文学" />
                  <el-option label="历史" value="历史" />
                  <el-option label="科技" value="科技" />
                  <el-option label="艺术" value="艺术" />
                  <el-option label="教育" value="教育" />
                  <el-option label="经济" value="经济" />
                  <el-option label="哲学" value="哲学" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="ISBN" prop="isbn">
                <el-input v-model="bookForm.isbn" placeholder="请输入ISBN" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 出版信息部分 -->
        <div class="form-section">
          <h3>出版信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="出版社" prop="publisher">
                <el-input v-model="bookForm.publisher" placeholder="请输入出版社" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出版日期" prop="publishDate">
                <el-date-picker
                  v-model="bookForm.publishDate"
                  type="date"
                  placeholder="请选择出版日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="页数" prop="pages">
                <el-input-number v-model="bookForm.pages" :min="1" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="价格" prop="price">
                <el-input-number
                  v-model="bookForm.price"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 库存信息 -->
        <div class="form-section">
          <h3>库存信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库存数量" prop="stock">
                <el-input-number v-model="bookForm.stock" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 图书介绍 -->
        <div class="form-section">
          <h3>图书介绍</h3>
          <el-form-item label="图书介绍" prop="description">
            <el-input
              v-model="bookForm.description"
              type="textarea"
              rows="5"
              placeholder="请输入图书介绍"
            />
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存修改' : '添加图书' }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBookDetail, addBook, updateBook } from '@/api/book'
import { ElMessage } from 'element-plus'

// 路由对象和路由实例
const route = useRoute()
const router = useRouter()
// 表单引用
const bookFormRef = ref(null)

// 判断是编辑模式还是添加模式
const isEdit = computed(() => !!route.params.id)
// 图书ID
const bookId = computed(() => route.params.id)

// 加载状态和提交状态
const loading = ref(false)
const submitting = ref(false)

// 图书表单数据
const bookForm = reactive({
  title: '',
  author: '',
  category: '',
  isbn: '',
  publisher: '',
  publishDate: '',
  pages: 0,
  price: 0,
  stock: 0,
  description: ''
})

// 表单验证规则
const rules = reactive({
  title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  isbn: [{ required: true, message: '请输入ISBN', trigger: 'blur' }],
  publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
  publishDate: [{ required: true, message: '请选择出版日期', trigger: 'change' }],
  pages: [{ required: true, message: '请输入页数', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
})

// 页面加载时，如果是编辑模式则获取图书详情
onMounted(() => {
  if (isEdit.value) {
    getBookData()
  }
})

// 获取图书详情数据
const getBookData = async () => {
  loading.value = true
  try {
    const res = await getBookDetail(bookId.value)
    if (res.code === 200) {
      // 填充表单数据
      Object.assign(bookForm, res.data)
    } else {
      ElMessage.error(res.msg || '获取图书详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取图书详情异常:', error)
    ElMessage.error('获取图书详情失败')
    goBack()
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  bookFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let res
        if (isEdit.value) {
          // 编辑模式：更新图书
          res = await updateBook(bookId.value, bookForm)
        } else {
          // 添加模式：新增图书
          res = await addBook(bookForm)
        }

        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '图书更新成功' : '图书添加成功')
          goBack()
        } else {
          ElMessage.error(res.msg || (isEdit.value ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('提交图书数据异常:', error)
        ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
      } finally {
        submitting.value = false
      }
    } else {
      ElMessage.warning('请填写完整的图书信息')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (isEdit.value) {
    // 编辑模式：重新获取图书数据
    getBookData()
  } else {
    // 添加模式：清空表单
    bookFormRef.value.resetFields()
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}
</script>

<style scoped>
.book-edit-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.book-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.form-section h3 {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.form-section:last-child {
  border-bottom: none;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}
</style> 